/**
 * 网络请求封装
 **/
import { ajaxForm } from './ajax.js'
import { Loading, Message, MessageBox } from 'element-ui'

const execAjax = (ajaxForm, url, objc) => {
    // loading
    let loadingInstance = null
    if (objc.loading) {
        loadingInstance = Loading.service({
            fullscreen: true,
            text: '拼命加载中...'
        })
    }

    ajaxForm[objc.method](url, objc.data)
        .then(res => {
            closeLoading(loadingInstance)
            objc.success && objc.success(res.data)
            if (objc.method === 'put') {
                Message({
                    center: true,
                    type: 'success',
                    message: '保存成功'
                })
            }
        })
        .catch(error => {
            closeLoading(loadingInstance)
            if (objc.showError && error.response.data && error.response.data.message) {
                Message({
                    type: 'error',
                    center: true,
                    message: error.response.data.message
                })
            } else {
                Message({
                    center: true,
                    message: '网络似乎有点忙，稍后在试'
                })
            }
            objc.fail && objc.fail(error.response.data)
        })
}

const formPost = (url, objc = {}) => {
    // 默认请求
    if (!objc.method) {
        objc.method = 'post'
    }

    // 发起请求
    if (objc.method === 'delete' || url.indexOf('/deletion') >= 0) {
        MessageBox.confirm('确定要删除数据么？', '删除提示', {
            type: 'warning'
        })
            .then(() => execAjax(ajaxForm, url, objc))
            .catch(() => console.log('取消删除'))
    } else {
        execAjax(ajaxForm, url, objc)
    }
}

const closeLoading = instance => {
    if (instance) {
        setTimeout(() => {
            instance.close()
        }, 500)
    }
}

export default formPost
